
{% set scriptLoader %}
function loadScript(url, type) {
  const s = document.createElement('script');
  s.src = url;
  s.onload = () => {
    document.dispatchEvent(new CustomEvent('scriptLoaded', {detail: {url}}));
  }
  if (type) {
    s.type = type;
  }
  if (type === 'module') {
    s.async = false; // Preserve load order.
    const pre = document.createElement('link');
    pre.rel = 'modulepreload';
    pre.href = url;
    document.head.append(pre);
    // We use DOMContentLoaded as the loader script is running sync, and inserting a module script here doesn't defer. This brings back normal type="module" behavior.
    window.addEventListener('DOMContentLoaded', () => {
      document.head.append(s);
    });
  } else {
    document.head.append(s);
  }
}
{% endset %}
<script>{{ scriptLoader | minifyJs | cspHash | safe }}</script>
